#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os
import json

from common.common_models import SubJobDetails
from exchange import log
from exchange.commons.const import SubJobStatusEnum, ParamConstant
from exchange.commons.common import output_execution_result_ex



class ExchangeBackupBase:
    def __init__(self, p_id, job_id, sub_job_id, json_param):
        self._p_id = p_id
        self._job_id = job_id
        self._sub_job_id = sub_job_id
        self._json_param = json_param
        self.cache_path = ""


    def get_cache_path(self):
        """
        从参数中获取cache仓的位置
        :return:
        """
        repositories = self._json_param.get("job", {}).get("repositories", [])
        for repo in repositories:
            if repo.get("repositoryType", "") == 2:
                self.cache_path = repo.get("path", [""])[0]
            if self.cache_path:
                break

    def write_progress_to_file(self, task_status, progress, log_detail, progress_type, total_size=0):
        log.info("Enter write_progress_to_file")
        if not self.cache_path:
            self.get_cache_path()
        output = SubJobDetails(taskId=self._job_id, subTaskId=self._sub_job_id, progress=int(progress),
                               logDetail=list(), taskStatus=task_status, dataSize=total_size)
        if log_detail:
            output.log_detail.append(log_detail)
        file_path = os.path.join(self.cache_path, progress_type)
        output_execution_result_ex(file_path, output.dict(by_alias=True))

    def report_progress_comm(self, file_name: str = None):
        log.info("Enter report_progress_comm")
        self.get_cache_path()
        if not self.cache_path:
            log.error("get_cache_path_filed.")
            return False
        # 默认查询common进度文件
        if not file_name:
            file_name = "common"
        file_path_comm = os.path.join(self.cache_path, file_name)
        try:
            if os.path.exists(file_path_comm):
                with open(file_path_comm, mode='r') as f:
                    log.info("report_progress before open!")
                    json_str = json.loads(f.read())
                    log.info("report_progress after open!")
            else:
                with open(file_path_comm, mode='w'):
                    log.info("report_progress creating file!!!")
                return True
        except Exception as err:
            log.error(err, exc_info=True)
            json_str = SubJobDetails(taskId=self._job_id, subTaskId=self._sub_job_id, progress=5,
                                     logDetail=list(), taskStatus=SubJobStatusEnum.FAILED.value).dict(by_alias=True)
        file_path = os.path.join(ParamConstant.RESULT_PATH, f"result{self._p_id}")
        output_execution_result_ex(file_path, json_str)
        return True